# -*- coding: UTF-8 -*-

##########################################################################
#
#   Copyright (c) 2020  Bresee, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###########################################################################
###########################################################################

# Wechat App Api

from flask import Blueprint
from flask import request
import utils.common.log as log
import json
import appapi.comm.create as vlogcreate
import utils.message.response as response
import utils.common.httpclient as httpclient
import utils.pgsql.pgcase
import time
# from datetime import datetime
import threading
import queue
from datetime import timedelta, datetime, date
import utils.pgsql.pgvlogrecord as record
import utils.pgsql.pgdevice as device
import redis
import utils.pgsql.pgadmin as pgadmin
import utils.pgsql.pgtemplate as template
import psycopg2

# 创建一个蓝图
tech_module = Blueprint("tech", __name__, url_prefix="/openapi/tech")


def locationTrans(sqlLocal) -> dict:
    """
    database locaiton format conversion : 
    {"lng": 120.121281, "lat": 30.222718}  
    ---> 
    {"lon": 120.121281, "lat": 30.222718}
    """
    dic = {}
    for key, value in sqlLocal.items():
        if key == "lng":
            dic["lon"] = value
        else:
            dic[key] = value
    return dic

# 用该蓝图来设置路由方法
@tech_module.route("/vlog/create", methods=["POST"])
def vlog_create():
    """ Scan your face to get a small video
    param type need  
    userId string yes  
    caseId string yes  
    location dict yes  
    channelId string yes  
    faceImgData string no  base64
    faceImgUrl string no  
    enableDuplicate boolean no true,false
    enableImgBeauty boolean no  
    optimalFramesNum Integer no  
    attributes json string no 
    {
    "openId":"outerUserId",
    "caseId":"caseid",
    "channelId":channelid, not exizt -1
    "location":{"lat":12.12344,"lon":150.4563245}
    "faceImgData":"data:xxxxx"
    }
    return param
    param type need 
    requestId string  
    success boolean  
    code string  
    msg string  
    data JSON
    {
    "requestId":"",
    "success":true,
    "code":"200",
    "msg":"success"
    "data":{
        "jobId":"abc123", // Job Id
        }
    }
    """
    dic = json.loads(request.data)
    log.logging.info("/vlog/create input param : userId :{} caseId :{} faceImgData len :{} \n".format(
            dic["params"]["userId"],
            dic["params"]["caseId"],
            len(dic["params"]["faceImgData"]),
        )
    )

    if "location" in dic["params"]:
        userLocation = dic["params"]["location"]
    else :
        userLocation = {}

    if "channelId" in dic["params"]:
        channelId = dic["params"]["channelId"]
    else :
        channelId = ""

    if "userId" in dic["params"]:
        jobId = vlogcreate.vlog_create(
            dic["params"]["faceImgData"],
            dic["params"]["userId"],
            dic["params"]["caseId"],
            "",
            userLocation,
            channelId

        )
    else:
        jobId = vlogcreate.vlog_create(
            dic["params"]["faceImgData"], "none", dic["params"]["caseId"], "",userLocation,channelId
        )
    print("jobId: {}".format(jobId))
    if jobId["code"] == 201:
        return response.make_response_success_no_data_tech()

    retDic = {"jobId": jobId["jobId"]["jobId"]}
    print("retDic: {}".format(retDic))
    return response.make_response_success_tech(retDic)


@tech_module.route("/job/view", methods=["POST"])
def job_view():
    """ 
    View vlog composition task details
    param type need discription
    requestId string  
    success boolean  
    code string  
    msg string  
    data JobResponse

    JobResponse
    {
    "jobId":"id123",
    "errorCode":"1000",
    "faceUrl":"xxx",
    "phase":"state",//PREPARE_MATERIAL,START_SYNTHESIS, FAILED,DONE
    "status":"NEW",//NEW,RUNNING,FAILED,DONE
    "products":[] }

    product

    productId String 
    jobId string taskid
    parentProductId string  
    rootProductId string  
    type String faceCheck,momentsCompose 
    templateId String  
    faceNumber integer  
    status String composing  done  failed 
    duration integer Video time (ms)
    thumbImageUrl String Media Preview
    videoUrl String video url
    progress integer Synthesis progress （0-100）
    {
    "requestId":"",
    "success":true,
    "code":"200",
    "msg":"success",
    "data":{
    "products":[
    {
    "jobId":"job id",
    "productId":"123456",
    "type":"faceCheck",
    "templateId":"fdfdf",
    "faceNumber":3,
    "status":"done",
    "videoUrl":"https://xxxxx",
    "thumbImageUrl":"https://xxxxx",
    "duration":30,
    "createDate":"2021-03-03",
    "lensExtra":[
        {
        "momentId":"XXX",
        "deviceId":"XXX"
        }
        ]
        },
        {
        "jobId":"task id",
        "productId":"123456",
        "type":"faceCheck",
        "templateId":"fdfdf",
        "faceNumber":3,
        "status":"composing"
        }
        ]
        }
        }

    """
    dic = json.loads(request.data)
    log.logging.info(" /job/view input dic : {} ".format(dic))

    status,ret_dic = httpclient.post_vlogclip_algorithm_query(dic) 

    log.logging.info(" /job/view ret_dic : {}".format(ret_dic))

    return response.make_response_success_tech(ret_dic)


@tech_module.route("/products/download", methods=["POST"])
def products_download():
    dic = json.loads(request.data)
    log.logging.info(" /products/download input dic : {} ".format(dic)) 
    status,ret_dic = httpclient.post_vlogclip_products_download(dic) 
    log.logging.info(" /products/download ret_dic : {}".format(ret_dic))

    return response.make_response_success_tech(ret_dic)

@tech_module.route("/job/download", methods=["POST"])
def job_download():
    dic = json.loads(request.data)
    log.logging.info(" /job/download input dic : {} ".format(dic)) 
    status,ret_dic = httpclient.post_vlogclip_algorithm_query(dic) 
    log.logging.info(" /job/download ret_dic : {}".format(ret_dic))

    return response.make_response_success_tech(ret_dic)



def get_case_info(caseId):
    """
    获取景区 info信息
    :return: info 前三段
    """
    dev_obj = device.PgDevice()
    info_dic = dev_obj.caseId_select_info(caseId)
    log.logging.info(' /case/view info_dic : {} '.format(info_dic))
    ret_inf0 =info_dic.get("info","")
    log.logging.info(' /case/view ret_inf0 : {} '.format(ret_inf0))
    if ret_inf0:
        inf0_list = ret_inf0.split("/")
        log.logging.info(' /case/view inf0_list : {} '.format(inf0_list))
        ret_inf0 = '/' + inf0_list[1]+'/'+inf0_list[2]+'/' +inf0_list[3]
    # print("ret_inf0",ret_inf0)
    return ret_inf0









# 获取所有景区
@tech_module.route("/case/list", methods=["POST"])
def case_list():
    # dic = json.loads(request.data)
    # techOperatorId = 1
    # ret, caseList = httpclient.get_web_getAllCaseByOperator(techOperatorId)

    case_obj = utils.pgsql.pgcase.PgCase()
    caseList = case_obj.tech_all()
    playgrounds = case_obj.get_playground()
    t_obj = template.PgTemplate()
    price_range ={}
    for k in t_obj.all():
        if not k['caseId'] in price_range:
            price_range[k['caseId']] = [k['ticketPrice']]
        else:
            price_range[k['caseId']].append(k['ticketPrice'])

    retCaseList = []
    for item in caseList:

        caseDic = {
            "caseId": str(item["caseId"]),
            "name": item["caseName"],
            "address": item["address"],
            "location": locationTrans(item["location"]),
            "caseType": item["type"],
            "description": item["description"],
            "descriptionMore": item["descriptionMore"],
            "coverImgUrl": item["coverImgUrl"],
            "coverImgUrlScale": item["coverImgUrlScale"],
            "ticketPrice": item["ticketPrice"],
            "AIfacilitator": item["AIfacilitator"],
            "AIUrl": item["AIUrl"],
            "notice": item["notice"],
            "propagateVideoUrl": item["propagateVideoUrl"],
            "price_tip": f"{item['ticketPrice']/100}元"
        }
        if item["caseId"] in  price_range:
            h_price = max(price_range[item["caseId"]])/100
            l_price = min(price_range[item["caseId"]])/100
            if l_price != h_price:
                price_tip = f"{l_price}-{h_price}元"
            else:
                price_tip = f"{l_price}元"
            caseDic["price_tip"] = price_tip
        caseDic['AIhttp'] = []
        tmp={
            '119.45.238.18':'https://api.skwhjt.com',
            '175.27.245.122':'https://bjyai122.skwhjt.com',
            '146.56.244.220':'https://bjyai133.skwhjt.com',
            '118.195.226.96':'https://bjyai144.zjskjt.com',
            '118.195.136.98':'https://bjyai155.skwhjt.com',
            '146.56.237.33': 'https://bjyai166.skwhjt.com',
            '119.45.63.226': 'https://bjyai177.skwhjt.com',
            '118.195.210.84': 'https://bjyai188.skwhjt.com',
            '119.45.156.201': 'https://bjyai199.skwhjt.com',
            '111.229.129.203': 'https://bjyai200.skwhjt.com',
        }
        for j in playgrounds:
            if j['case_id'] == item['caseId']:
                one_AIUrl = j['ai_ip'].strip()
                if one_AIUrl:
                    # 一个景区两个项目上线在同一套算法出现两个相同 AIhttp
                    if tmp[one_AIUrl] in caseDic['AIhttp']:
                        continue
                    else:
                        caseDic['AIhttp'].append(tmp[one_AIUrl])



        info_str = get_case_info(item["caseId"]) if caseDic['AIhttp'] else ""
        caseDic["province"] = info_str
        retCaseList.append(caseDic)

    ret_dic = {
        "pageSize": len(retCaseList),
        "pageNo": 1,
        "total": len(retCaseList),
        "items": retCaseList,
    }

    # log.logging.info(' /case/list ret_dic : {} '.format(ret_dic))
    return response.make_response_success_tech(ret_dic)



# 获取指定景区信息
@tech_module.route("/case/view", methods=["POST"])
def case_view():
    dic = json.loads(request.data)

    """Query the details of scenic spots managed by ISV applications
    获取知道景区详情 """
    caseId = int(dic["params"]["caseId"])

    obj = utils.pgsql.pgcase.PgCase()
    caseInfo = obj.get(caseId)
    ret, pointInfo = httpclient.get_web_getCasePoint(caseId)
    playgrounds = obj.get_playground()
    # print(caseInfo)
    cameraPositions = []
    for item in pointInfo:
        point = {
            "name": item["pointName"],
            "location": locationTrans(item["location"]),
            "thumbnailUrl": item["coverImgPath"],
            "description": item["description"],
            "playIntroduce": [],
        }
        cameraPositions.append(point)
    retCaseList = []
    caseDic = {
        "caseId": caseId,
        "name": caseInfo["caseName"],
        "address": caseInfo["address"],
        "location": locationTrans(caseInfo["location"]),
        "caseType": caseInfo["type"],
        "description": caseInfo["description"],
        "descriptionMore": caseInfo["descriptionMore"],
        "coverImgUrl": caseInfo["coverImgUrl"],
        "coverImgUrlScale": caseInfo["coverImgUrlScale"],
        "ticketPrice": caseInfo["ticketPrice"],
        "AIfacilitator": caseInfo["AIfacilitator"],
        "AIUrl": caseInfo["AIUrl"],
        "cameraPositions": cameraPositions,
    }
    # if caseDic['AIUrl'] == '119.45.238.18':
    #     caseDic['AIhttp'] = 'https://api.skwhjt.com'
    #
    # elif caseDic['AIUrl'] == '175.27.245.122':
    #     caseDic['AIhttp'] = 'https://bjyai122.skwhjt.com'
    #
    # elif caseDic['AIUrl'] == '146.56.244.220':
    #     caseDic['AIhttp'] = 'https://bjyai133.skwhjt.com'

    caseDic['AIhttp'] = []
    tmp = {
        '119.45.238.18': 'https://api.skwhjt.com',
        '175.27.245.122': 'https://bjyai122.skwhjt.com',
        '146.56.244.220': 'https://bjyai133.skwhjt.com',
        '118.195.226.96': 'https://bjyai144.zjskjt.com',
        '118.195.136.98': 'https://bjyai155.skwhjt.com',
        '146.56.237.33': 'https://bjyai166.skwhjt.com',
        '119.45.63.226': 'https://bjyai177.skwhjt.com',
        '118.195.210.84': 'https://bjyai188.skwhjt.com',
        '119.45.156.201': 'https://bjyai199.skwhjt.com',
        '111.229.129.203': 'https://bjyai200.skwhjt.com',
    }
    for j in playgrounds:
        if j['case_id'] == caseId:
            one_AIUrl = j['ai_ip'].strip()
            if one_AIUrl:
                # 一个景区两个项目上线在同一套算法出现两个相同 AIhttp
                if tmp[one_AIUrl] in caseDic['AIhttp']:
                    continue
                else:
                    caseDic['AIhttp'].append(tmp[one_AIUrl])


    info_str = get_case_info(caseId)
    caseDic["province"] = info_str
    retCaseList.append(caseDic)


    ret_dic = {
        "pageSize": len(retCaseList),
        "pageNo": 1,
        "total": len(retCaseList),
        "items": retCaseList,
    }

    # log.logging.info(' /case/view ret_dic : {} '.format(ret_dic))
    return response.make_response_success_tech(ret_dic)


@tech_module.route("/data/buriedpoint", methods=["POST"])
def data_buriedpoint():
    dic = json.loads(request.data)
    log.logging.info(" /data/buriedpoint input dic : {} ".format(dic))

    msg = json.dumps(dic)
    queue = "buriedpoint_data"
    ret_dic = dic
    return response.make_response_success_tech(ret_dic)

def deviation_date(date, offsets):
    start_date = datetime.strptime(date, "%Y-%m-%d")
    now_date = timedelta(days=offsets)
    a = start_date + now_date
    return a.strftime("%Y-%m-%d")

 
@tech_module.route("/getuserdata", methods=["POST"])
def getuserdata():
    dic = json.loads(request.data)
    limit = dic.get("limit", "") #小程序H5也要根据项目查数据
     
    end_date = dic["date"][0]
    # begin_date = dic["date"][0]
    endDate = end_date[:4] + end_date[5:7] + end_date[8:]
    # beginDate = begin_date[:4] + begin_date[5:7] + begin_date[8:]

   
    payUsers = {"totalCount": 0, "dayInfo": []}
    payVideos = {"totalCount": 0, "dayInfo": []}
    composeUsers = {"totalCount": 0, "dayInfo": []}
    composeVideos = {"totalCount": 0, "dayInfo": []}
    cashFee = {"totalCount": 0, "dayInfo": []}
    userPaymentRate = {"totalCount": 0, "dayInfo": []}
    videoPaymentRate = {"totalCount": 0, "dayInfo": []}


    datalist = str(datetime.strptime(deviation_date(end_date, -2), "%Y-%m-%d")).split(" ")[0].split("-")
    beginDate = "".join(datalist)
    begin_date = deviation_date(end_date, -2)
    # cache = redis.Redis(host='10.206.0.115', port=6379, db=10, password='SKadmin123_456')
    # t1 = cache.get(request.headers["Authorization"])  # b'929'
    # limit = ""
    # if t1:
    #     admin_id = int(t1)
    #     obj = pgadmin.PgAdmin()
    #     user_dic = obj.get(admin_id)
    #     limit = user_dic['playground_limit']

      
    data = {
        "ref_date": f"{beginDate}-{endDate}",
        "caseId": dic["caseId"],
        "payUsers": payUsers,
        "payVideos": payVideos,
        "composeUsers": composeUsers,
        "composeVideos": composeVideos,
        "cashFee": cashFee,
        "userPaymentRate":userPaymentRate,
        "videoPaymentRate":videoPaymentRate
    }

    obj = record.PgRecord()
     
    while begin_date <= end_date:
        
        compose = obj.casecompose(
            dic["caseId"],
            datetime.strptime(begin_date, "%Y-%m-%d"),
            datetime.strptime(deviation_date(begin_date, +1), "%Y-%m-%d"),
            limit=limit
        )
       
        data["composeVideos"]["totalCount"] += len(compose)
        data["composeVideos"]["dayInfo"].append(
            {"count": len(compose), "time": begin_date}
        )
        composeuser = []
     
        for i in compose:
            if i["userId"] not in composeuser:
                composeuser.append(i["userId"])
        data["composeUsers"]["totalCount"] += len(composeuser)
        data["composeUsers"]["dayInfo"].append(
            {"count": len(composeuser), "time": begin_date}
        )

   
        pay = obj.paycase(
            dic["caseId"],
            datetime.strptime(begin_date, "%Y-%m-%d"),
            datetime.strptime(deviation_date(begin_date, +1), "%Y-%m-%d"),
            limit=limit
        )

        data["payVideos"]["totalCount"] += len(pay)
        data["payVideos"]["dayInfo"].append({"count": len(pay), "time": begin_date})
        payuser = []
        cashFeeall = 0   
     
        for i in pay:
            cashFeeall += i["totalFee"] / 100
            if i["openId"] not in payuser:
                payuser.append(i["openId"])

     
        data["payUsers"]["totalCount"] += len(payuser)
        data["payUsers"]["dayInfo"].append({"count": len(payuser), "time": begin_date})

     
        data["cashFee"]["totalCount"] += cashFeeall
        cashFeeall = round(cashFeeall, 2)
        data["cashFee"]["totalCount"] = round(data["cashFee"]["totalCount"], 2)
        data["cashFee"]["dayInfo"].append({"count": cashFeeall, "time": begin_date})
        if len(composeuser)!=0:
            data["userPaymentRate"]["dayInfo"].append({"count":  str(round(len(payuser)/len(composeuser)*100,2))+"%", "time": begin_date})

            data["videoPaymentRate"]["dayInfo"].append({"count": str(round(len(pay)/len(composeuser)*100,2))+"%", "time": begin_date})
        else:
            data["userPaymentRate"]["dayInfo"].append({"count":  "0.00%", "time": begin_date})

            data["videoPaymentRate"]["dayInfo"].append({"count": "0.00%", "time": begin_date})
            
       
        begin_date = deviation_date(begin_date, +1)
    if data["composeUsers"]["totalCount"] !=0:
            data["userPaymentRate"]["totalCount"]= str(round(data["payUsers"]["totalCount"]/data["composeUsers"]["totalCount"]*100,2))+"%"

            data["videoPaymentRate"]["totalCount"]=str(round(data["payVideos"]["totalCount"]/data["composeUsers"]["totalCount"]*100,2))+"%"
    else:
            data["userPaymentRate"]["totalCount"]= "0.00%"

            data["videoPaymentRate"]["totalCount"]= "0.00%"
    

    return response.make_response_success(data)


# 获取url 对应机位数
@tech_module.route("/url/faceNum", methods=["POST"])
def url_faceNum():
    dic = json.loads(request.data)

    """根据url查询老平台数据 """
    MediaURLPreview = dic.get("MediaURLPreview")
    # 链接数据库 - 老平台
    log.logging.info("MediaURLPreview:" +MediaURLPreview)


    obj = utils.pgsql.pgvlogrecord.PgRecord()
    faceNumInfo = obj.get_url_faceNum(MediaURLPreview)
    log.logging.info("faceNumInfo:" + str(faceNumInfo))


    return response.make_response_success_tech(faceNumInfo)














